package game;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.io.*;
import java.awt.event.MouseListener ;
import java.awt.event.MouseEvent ;
import java.awt.event.InputEvent ;
import java.awt.image.MemoryImageSource;
import javax.swing.Timer;
import javax.swing.ImageIcon;

public class Ultimatum extends Game {
    int count;
    Random generator;
    BufferedReader din;
    Double money_won = 0.0 , p1_init_money = 0.0, money_passed = 0.0;
    BufferedReader bin ;
    String state ;

    double increment;
    int totalTime=60,secs = totalTime, timeTaken=0;
    Timer time = new Timer(1000, new TimeListener());

	/** The amount of money the opponent wins. */
	double oppMoney;

	/** List of values that user can choose to send. Used in chooser JList. */
	LinkedList<String> moneyValues = new LinkedList<String>();

	/** Number of values to display in the chooser JList. */
	final int LIST_SIZE = 5;

	/** Half of list size. */
	int halfList;

	/** Maximum number of values the user could possibly choose given the
	 increment, and starting and stopping values. */
	int maxValues;

	/** List index we've displayed for the chooser list. */
	int listIndex = 0;

	/** Whether player 2 accepts or rejects the amount. */
	int p2Result;

	// Game log constants.
	final int GL_P2_ACCEPT = 1;
	final int GL_P2_REJECT = 0;

	public Ultimatum (String params, int currentRep) {
		super();
//    super("",
//              false, //resizable
//              false, //closable
//              false, //maximizable
//              false);//iconifiable
//        javax.swing.plaf.InternalFrameUI ui = this.getUI();
//        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

		this.state = "1" ;
		
		String paramPart[] = params.split (",");
        p1_init_money = Double.parseDouble (paramPart[2]);
        increment = Double.parseDouble (paramPart[3]);
		this.params = params;
		repTot = Integer.parseInt (paramPart[1]);
		repNum = currentRep;
		
        initComponents();
        l3.setText(String.format ("$%.2f", p1_init_money));
        this.setVisible(true);
        setLocation(screenSize.width/2-400, screenSize.height/2-300);
        
        runner.addMouseListener( new Ultimatum.CheckMouse() ) ;
        addMouseListener( new Ultimatum.CheckMouse() ) ;
		this.getGlassPane().addMouseListener(new Ultimatum.CheckMouse());

		// Assuming no loss of precision.
		maxValues = (int) (p1_init_money / increment) + 1;
		halfList = (int) Math.floor (LIST_SIZE / 2);
		int numValues = maxValues - halfList + LIST_SIZE;
		for (listIndex = maxValues-halfList;
			listIndex < numValues; listIndex++) {
			moneyValues.add (String.format ("$%.2f",
				increment * (listIndex % maxValues)));
		}
		moneyList.setListData(moneyValues.toArray(new String [LIST_SIZE]));
		moneyList.setSelectedIndex(halfList);
		moneyList.addMouseListener (new Ultimatum.CheckMouse());

        l11.setIcon(new ImageIcon(this.getClass().getResource("/images/redAddMoney.png")));
        l10.setIcon(new ImageIcon(this.getClass().getResource("/images/greenGive.png")));

        time.start();
        int min = secs/60;
        int sec = secs%60;
        lblTime.setText(min+":"+((sec<10)?"0":"")+sec);

        hideMouse();
    }

    /** Creates new form Dictator */
    public Ultimatum() {
        super();
//        super("",
//              false, //resizable
//              false, //closable
//              false, //maximizable
//              false);//iconifiable
//        javax.swing.plaf.InternalFrameUI ui = this.getUI();
//        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        this.state = "1" ;
        this.p1_init_money = 4.0;
        increment = 0.25;
        initComponents();
        l3.setText(Double.toString(p1_init_money));
        this.setVisible(true);
        setLocation(screenSize.width/2-400, screenSize.height/2-300);

        addMouseListener( new Ultimatum.CheckMouse() ) ;
        l11.setIcon(new ImageIcon(this.getClass().getResource("/images/redAddMoney.png")));
        l10.setIcon(new ImageIcon(this.getClass().getResource("/images/greenGive.png")));

        time.start();
        int min = secs/60;
        int sec = secs%60;
        lblTime.setText(min+":"+((sec<10)?"0":"")+sec);

        hideMouse();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        l2 = new javax.swing.JLabel();
        l3 = new javax.swing.JLabel();
        l4 = new javax.swing.JLabel();
        l5 = new javax.swing.JLabel();
        l11 = new javax.swing.JLabel();
        l10 = new javax.swing.JLabel();
        lblTime = new javax.swing.JLabel();
        moneyScroll = new javax.swing.JScrollPane();
        moneyList = new javax.swing.JList();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(null);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        l2.setFont(new java.awt.Font("Calibri", 1, 28)); // NOI18N
        l2.setForeground(new java.awt.Color(0, 51, 255));
        l2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        l2.setText("You have");

        l3.setFont(new java.awt.Font("Calibri", 1, 28));
        l3.setForeground(new java.awt.Color(51, 102, 255));

        l4.setFont(new java.awt.Font("Calibri", 1, 28));
        l4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        l4.setText("How much would you like to give to the other player?");

        l5.setFont(new java.awt.Font("Calibri", 1, 28));
        l5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        l11.setFont(new java.awt.Font("Trebuchet MS", 1, 24));
        l11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/redSelect.png"))); // NOI18N

        l10.setFont(new java.awt.Font("Trebuchet MS", 1, 24));
        l10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/greenPass.png"))); // NOI18N

        lblTime.setFont(new java.awt.Font("Calibri", 1, 36));
        lblTime.setForeground(new java.awt.Color(153, 102, 0));
        lblTime.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/hrGlass.png"))); // NOI18N
        lblTime.setText("3:00");

        moneyList.setFont(new java.awt.Font("Tahoma", 1, 24));
        moneyList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "$0.00", "$0.25", "$0.50", "$0.75", "$1.00" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        moneyList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        moneyList.setVisibleRowCount(5);
        moneyList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                moneyListValueChanged(evt);
            }
        });
        moneyScroll.setViewportView(moneyList);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(299, 299, 299)
                                .add(l2)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(l3))
                            .add(l4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                            .add(lblTime, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                            .add(l5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(95, 95, 95)
                                .add(l11)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 143, Short.MAX_VALUE)
                                .add(l10)
                                .add(76, 76, 76)))
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(moneyScroll, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 123, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(332, 332, 332))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(lblTime, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(47, 47, 47)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(l3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(l2))
                .add(42, 42, 42)
                .add(l4)
                .add(46, 46, 46)
                .add(moneyScroll, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(28, 28, 28)
                .add(l5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 71, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(l11)
                    .add(l10))
                .add(50, 50, 50))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	/**
	 * Don't let subject change the value of the list.
	 *
	 * @param evt
	 */
	private void moneyListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_moneyListValueChanged
		moneyList.setSelectedIndex(halfList);
}//GEN-LAST:event_moneyListValueChanged

    @Override
    public synchronized void addMouseListener(MouseListener l) {
        super.addMouseListener(l);
    }

	/**
     * Shift the money list to increase by one place.
     */
    private void incrementMoneyList() {
		listIndex++;
		moneyValues.remove();
		moneyValues.add (String.format ("$%.2f",
			increment * (listIndex % maxValues)));
		moneyList.setListData (
			moneyValues.toArray(new String [LIST_SIZE]));
		moneyList.setSelectedIndex (halfList);
    }

    class CheckMouse implements MouseListener{
        public void mousePressed(MouseEvent e) { hideMouse(); }
         public void mouseReleased(MouseEvent e) {}
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mouseClicked(MouseEvent e) {
            int modifiers = e.getModifiers();
            if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
                if( state.equals( "1" )) {
					incrementMoneyList();
					String moneyStr =
						moneyList.getSelectedValue().toString().substring (1);
                    money_passed = Double.parseDouble (moneyStr);
                }
                if( state.equals( "2" )) {}    //
            }
            if ((modifiers & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) {}
            if ((modifiers & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
                if (state.equals( "2" )) {
                    
                }
                if (state.equals( "1" )) {
                    state = "2" ;
                    System.out.println("State" + state);
                    state = "3" ;
                    l5.setText("Money Sent.");
                    timeTaken = totalTime - secs;
                    calculateResult();
					writeLog (playerId + ",1,\"" + params + "\"," + repNum
						+ "," + repTot + ","
						+ String.format ("$%.2f", money_won) + ","
						+ String.format ("$%.2f", oppMoney));
					writeGameLog (playerId + ",1," + timeTaken + ","
						+ String.format ("$%.2f", money_passed) + ","
						+ p2Result);
                    totalMoneyWon += money_won ;
                    System.out.println("G.totalMoneyWon = " + totalMoneyWon) ;
                    secs=0;
                    l10.setVisible(false);
                    l11.setVisible(false);
                    /*We have to add here the message that the game is done and press next... */
                }
           }
        }
    }

    class TimeListener implements ActionListener {
    	 public void actionPerformed(ActionEvent e) {
    		secs--;
            if(secs>=0) {
                int min = secs/60;
                int sec = secs%60;
                lblTime.setText(min+":"+((sec<10)?"0":"")+sec);
            }
            if(secs==0) {
                //time.stop();
                l11.setVisible(false);
                l10.setVisible(false);
                state="2";
                l2.setText(null);
                l3.setText(null);
                moneyList.setVisible (false);
				moneyScroll.setVisible (false);
                l4.setText("Sorry, your time is up.");
                writeLog (playerId + ",1,\"" + params + "\"," + repNum
					+ "," + repTot + ",TimeOut,TimeOut");
				writeGameLog (playerId + ",1," + timeTaken
					+ ",TimeOut,TimeOut");
                totalMoneyWon += 0.0 ;
                System.out.println("G.totalMoneyWon = " + totalMoneyWon) ;
            }
            if(secs==-6) {
                time.stop();
                try {
                    setVisible(false);
                    free=true;
                } catch(Exception ex) {
                    ex.printStackTrace();
                    logError(ex);
                }
            }
    	}

    }

    private void hideMouse() {
        int[] pixels = new int[16 * 16];
        Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
        Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisibleCursor");
        this.getGlassPane().setCursor(transparentCursor);
		this.getGlassPane().setVisible(true);
        runner.setCursor(transparentCursor);
    }

    public void calculateResult() {
        String line ;
        bin = readGameData() ;
        System.out.println("money_passed: " + money_passed);
        try {
            line = bin.readLine() ;
            line = bin.readLine() ;
            while( line != null ) {
                String str[] = line.split(",") ; 
                if( money_passed == Double.parseDouble(str[0]) ){
                    System.out.println("Match: " + str[0] );
                    generator = new Random();
                    double choice;
                    choice = generator.nextDouble() ;
                    System.out.println("Choice: " + choice);
                    System.out.println("Probability: " + str[1]);
                    if( choice > Double.parseDouble(str[1]) ){
                        money_won = 0.0 ;
						oppMoney = 0.0;
                        System.out.println("Result: Loses");
						p2Result = GL_P2_REJECT;
                    }else{
                        money_won = p1_init_money - money_passed ;
						oppMoney = money_passed;
                        System.out.println("Result: Wins");
						p2Result = GL_P2_ACCEPT;
                    }
                    System.out.println("money_won: " + money_won);
                    break ;
                }
                line = bin.readLine() ;
            }
        }catch( Exception e ){
             e.printStackTrace();
             logError(e);
         }
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        /*java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JFrame main = new JFrame();
                    JDesktopPane dPane = new JDesktopPane();
                    Ultimatum frame = new Ultimatum();
                    main.setSize(820, 620);
                    dPane.add(frame);
                    main.add(dPane);
                    main.setVisible(true);
                    dPane.setVisible(true);
                    frame.setSelected(true);
                    frame.setVisible(true);
                } catch(Exception ex) {
                    ex.printStackTrace();
                };
            }
        });*/
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel l10;
    private javax.swing.JLabel l11;
    private javax.swing.JLabel l2;
    private javax.swing.JLabel l3;
    private javax.swing.JLabel l4;
    private javax.swing.JLabel l5;
    private javax.swing.JLabel lblTime;
    private javax.swing.JList moneyList;
    private javax.swing.JScrollPane moneyScroll;
    // End of variables declaration//GEN-END:variables
}
